#include <pthread.h>
#include <memory>
#include "Socket.hpp"  // 确保已修正Recive为Receive的拼写错误
using namespace SocketModule;
using ConnectSocketPtr = std::shared_ptr<TCPConnectSocket>;

void Usage(const std::string &name)
{
    std::cout << "usage: " << name << " + port" << std::endl;
}

// 线程函数：接收参数为shared_ptr的副本（确保对象存活）
void* Server(void* args)
{
    pthread_detach(pthread_self());
    ConnectSocketPtr con_socket = *static_cast<ConnectSocketPtr*>(args);
    delete static_cast<ConnectSocketPtr*>(args);

    std::string recv_msg;
    InetAddr client = con_socket->addr();
    while(true)
    {
        int size = con_socket->Receive(recv_msg);
        if (recv_msg.empty())  // 处理连接关闭或错误
        {
            LOG(LogLevel::INFO) << "[" << client.Info() << "] 断开连接";
            break;
        }
        LOG(LogLevel::INFO) << "[" << client.Info() << "]# " << recv_msg;
        con_socket->Send(recv_msg);  // 回显数据
    }
    return nullptr;
}

int main(int argc, char* args[])
{
    if (argc != 2)
    {
        Usage(args[0]);
        exit(USAGE_ERROR);
    }
    in_port_t port = std::stoi(args[1]);
    TCPListenSocket lis_socket(port);

    while(true)
    {
        ConnectSocketPtr con_socket = lis_socket.Accept();
        if (!con_socket)  // 处理accept失败的情况
        {
            continue;
        }
        // 传递shared_ptr的副本到堆上，避免局部变量生命周期问题
        pthread_t thread;
        pthread_create(&thread, nullptr, Server, new ConnectSocketPtr(con_socket));
    }

    return 0;
}